const _ = require('lodash');
import { AlarmLimit, ModalConfirm, ScreenAreaPatientMsg } from '@/components';
import EcgCharts from '@/components/EcgCharts';
import EcgModule from '@/components/EcgModule';
import { ALARM_THRESHOLD_MAP,wsUrl } from '@/constants';
import { getScreenAreaList, SystemSettingsGetInfo } from '@/services/common';
import { patientDischarged } from '@/services/patientMsg';
import { EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';

import { Dropdown, message, Popconfirm } from 'antd';
import dayjs from 'dayjs';
import { stringify } from 'querystring';
import { useEffect, useRef, useState } from 'react';
import closeNotice from '../../../public/images/closeNotice.png';
import manPng from '../../../public/images/man.png';
import partMsg from '../../../public/images/partMsg.png';
import womanPng from '../../../public/images/woman.png';
import highMp3 from '../../../public/mp3/high.mp3';
import middleMp3 from '../../../public/mp3/middle.mp3';
import './index.less';

/**
 * productModel 产品型号 Dock => k1  海上120 =》ZCHS-HS120-DCJH-001 便携式Max bxsMax
 */
let timer: any = null;
let setIntervalFun: any = null;
let checkWebSocketFun: any = null;
let setIntervalFunCloseFlag = 0; // 关闭定时器的标志位
let sendWsDataInterval: any = null;

export default function DashBoardPage() {
  const [nowTime, setNowTime] = useState('');
  const [screenAreaList, setScreenAreaList] = useState<any>([]); //分区列表
  const [scketSuccessFlag, setScketSuccessFlag] = useState<boolean>(false);
  let socketDataRef: any = useRef();
  const wsRef = useRef<any>(null); // 用于管理WebSocket连接
  const useInfo: any = window.sessionStorage.getItem('userInfo') || '{}';
  const deptId = JSON.parse(useInfo)?.deptId;
  const urlParams = new URL(window.location.href).searchParams;
  const pageNum: any = urlParams.get('pageNum') || 1;
  // 创建音频元素的引用
  const [alarmLevel, setAlarmLevel] = useState<any>(0);
  const playAlarmintervalRef: any = useRef(null);
  const videoRef: any = useRef(null);
  const [systemSettings, setSystemSettings] = useState<any>({});
  const [modItem, setmodItem] = useState<any>(null);
  const ScreenAreaPatientMsgRef = useRef<any>(null);
  const AlarmLimitRef = useRef<any>(null);
  const modalConfirmRef = useRef<any>(null);
  const currentIndex = useRef<any>([0, 0]);
  const intervalRef: any = useRef(null);

  const initData = async () => {
    // 获取当前时间
    timer = window.setInterval(() => {
      setNowTime(dayjs().format('YYYY/MM/DD HH:mm:ss'));
    }, 1000);
    const SystemSettingsGetInfoRes = await SystemSettingsGetInfo();
    if (SystemSettingsGetInfoRes?.code === 200) {
      setSystemSettings(SystemSettingsGetInfoRes?.data);
      const systemPageSize = SystemSettingsGetInfoRes?.data?.systemPageSize;
      const res = await getScreenAreaList({
        pageNum: pageNum,
        pageSize: systemPageSize,
      });
      if (res?.code === 200) {
        const data = res.rows;
        if (data) {
          setScreenAreaList(data);
        }
      }
    }
  };
  const CreateMultipleCon = () => {
    if (wsRef.current && screenAreaList.length > 0 && deptId) return; // 避免重复连接
    const ws = new WebSocket(
      `${wsUrl}/ws3/${deptId}/${pageNum}/${
        systemSettings?.systemPageSize || 9
      }`,
    );
    wsRef.current = ws;
    ws.onopen = () => {
      console.log(`WebSocket connected`);
      setScketSuccessFlag(true);
    };
    ws.onmessage = (event) => {
      const data = event.data ? JSON.parse(event.data) : [];
      setIntervalFunCloseFlag = 0;
      console.log(data, '发送得消息');
      console.log(
        dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss:SSS'),
        '当前时间',
      );
      const targetData = data.map((its: any) => {
        const existingItem = socketDataRef.current?.find(
          (item: any) => item.ip === its.ip,
        );
        const existingWaveform = existingItem?.ecgWaveform || {};
        const newWaveform = its.ecgWaveform || {};
        const mergedWaveform: any = {};

        // 合并所有导联数据
        for (const key in newWaveform) {
          if (
            Array.isArray(existingWaveform[key]) &&
            Array.isArray(newWaveform[key])
          ) {
            mergedWaveform[key] = [
              ...existingWaveform[key],
              ...newWaveform[key],
            ];
          } else {
            mergedWaveform[key] =
              newWaveform[key] || existingWaveform[key] || [];
          }
        }

        // 保留旧数据中可能存在的其他属性
        for (const key in existingWaveform) {
          if (!mergedWaveform[key]) {
            mergedWaveform[key] = existingWaveform[key];
          }
        }
        //合并呼吸波数据
        const existingRespirationWaveform =
          existingItem?.respirationWaveform || [];
        const newRespirationWaveform = its.respirationWaveform || [];
        let mergedRespirationWaveform: any = [];
        if (
          Array.isArray(existingRespirationWaveform) &&
          Array.isArray(newRespirationWaveform)
        ) {
          mergedRespirationWaveform = [
            ...existingRespirationWaveform,
            ...newRespirationWaveform,
          ];
        }
        //合并血氧波数据
        const existingSpo2Waveform = existingItem?.spo2Waveform || [];
        const newSpo2Waveform = its.spo2Waveform || [];
        let mergedSpo2Waveform: any = [];
        if (
          Array.isArray(existingSpo2Waveform) &&
          Array.isArray(newSpo2Waveform)
        ) {
          mergedSpo2Waveform = [...existingSpo2Waveform, ...newSpo2Waveform];
        }
        return {
          ip: its.ip,
          ecgWaveform: mergedWaveform,
          respirationWaveform: mergedRespirationWaveform,
          spo2Waveform: mergedSpo2Waveform,
          heartRate: its.heartRate
            ? its.heartRate
            : existingItem?.heartRate || '-',
          respirationRate: its.respirationRate
            ? its.respirationRate
            : existingItem?.respirationRate || '-',
          spo2Value: its.spo2Value
            ? its.spo2Value
            : existingItem?.spo2Value || '-',
          temperature1: its.temperature1
            ? its.temperature1
            : existingItem?.temperature1 || '-',
          temperature2: its.temperature2
            ? its.temperature2
            : existingItem?.temperature2 || '-',
          status: its.status,
          alarms: its.alarms || [],
          productModel: its.productModel, // 产品型号
          maxAlarmLevel: its.maxAlarmLevel, // 最大报警等级
        };
      });
      socketDataRef.current = _.cloneDeep(targetData);
    };
    ws.onerror = (error) => {
      console.error(`WebSocket error for patient`, error);
      setScketSuccessFlag(false);
    };

    ws.onclose = () => {
      console.log(`WebSocket closed`);
      setScketSuccessFlag(false);
      wsRef.current = null;
    };

    return () => {
      ws.close();
      wsRef.current = null;
    };
  };
  const drawIntervalFun = () => {
    setIntervalFun = window.setInterval(() => {
      let maxAlarmLevelTarget = 0; // 最大报警等级
      setIntervalFunCloseFlag = setIntervalFunCloseFlag + 1;
      if (setIntervalFunCloseFlag > 1500 && setIntervalFun) {
        window.clearInterval(setIntervalFun);
        setIntervalFun = null;
        setTimeout(() => {
          if (wsRef.current) return; // 已连接则跳过
          CreateMultipleCon(); // 复用创建连接的函数
        }, 3000); // 3秒后重连
        return;
      }
      if (socketDataRef.current) {
        const oldSocketData = _.cloneDeep(socketDataRef.current);
        const data = _.cloneDeep(oldSocketData).map((its: any) => {
          let fluctuateNum = 19; // 波动幅度
          if (its.productModel && its.productModel.includes('bxs')) {
            fluctuateNum = 39;
          } else if (
            its.productModel &&
            its.productModel.includes('ZCHS-HS120-DCJH-001')
          ) {
            fluctuateNum = 9;
          }
          for (const key in its.ecgWaveform) {
            if (its.ecgWaveform[key].length <= 2000) {
              its.ecgWaveform[key] = its.ecgWaveform[key].splice(
                0,
                fluctuateNum,
              );
            } else {
              its.ecgWaveform[key] = its.ecgWaveform[key].splice(
                0,
                fluctuateNum * 2,
              );
            }
          }
          // 呼吸波形
          if (its.respirationWaveform) {
            its.respirationWaveform =
              its?.respirationWaveform?.length <= 2000
                ? its.respirationWaveform.splice(0, fluctuateNum)
                : its.respirationWaveform.splice(0, fluctuateNum * 2);
          }
          // 血氧波形
          if (its.spo2Waveform) {
            if (its.productModel && its.productModel.includes('bxs')) {
              its.spo2Waveform =
                its.spo2Waveform.length <= 2000
                  ? its.spo2Waveform.splice(0, 4)
                  : its.spo2Waveform.splice(0, 8);
            } else {
              its.spo2Waveform =
                its.spo2Waveform.length <= 2000
                  ? its.spo2Waveform.splice(0, fluctuateNum)
                  : its.spo2Waveform.splice(0, fluctuateNum * 2);
            }
          }
          return its;
        });
        const targetSocketData = _.cloneDeep(socketDataRef.current).map(
          (itsval: any) => {
            let fluctuateNum = 19; // 波动幅度
            if (itsval.productModel && itsval.productModel.includes('bxs')) {
              fluctuateNum = 39;
            } else if (
              itsval.productModel &&
              itsval.productModel.includes('ZCHS-HS120-DCJH-001')
            ) {
              fluctuateNum = 9;
            }
            for (const keyval in itsval.ecgWaveform) {
              if (itsval.ecgWaveform[keyval].length <= 2000) {
                itsval.ecgWaveform[keyval].splice(0, fluctuateNum);
              } else {
                itsval.ecgWaveform[keyval].splice(0, fluctuateNum * 2);
              }
            }
            // 呼吸波形
            if (itsval?.respirationWaveform) {
              itsval?.respirationWaveform?.length <= 2000
                ? itsval.respirationWaveform.splice(0, fluctuateNum)
                : itsval.respirationWaveform.splice(0, fluctuateNum * 2);
            }
            // 血氧波形
            if (itsval?.spo2Waveform) {
              if (itsval.productModel && itsval.productModel.includes('bxs')) {
                itsval.spo2Waveform.length <= 2000
                  ? itsval.spo2Waveform.splice(0, 4)
                  : itsval.spo2Waveform.splice(0, 8);
              } else {
                itsval.spo2Waveform.length <= 2000
                  ? itsval.spo2Waveform.splice(0, fluctuateNum)
                  : itsval.spo2Waveform.splice(0, fluctuateNum * 2);
              }
            }
            return itsval;
          },
        );
        socketDataRef.current = _.cloneDeep(targetSocketData);
        let targetScreenAreaList = _.cloneDeep(screenAreaList);
        for (let i = 0; i < data.length; i++) {
          const targetItem = screenAreaList.find((its: any) => {
            return its?.device?.ip == data[i].ip;
          });
          if (targetItem) {
            const ipIndex = screenAreaList.findIndex((its: any) => {
              return targetItem.id == its.id;
            });
            if (
              ipIndex >= 0 &&
              targetScreenAreaList[ipIndex] &&
              targetScreenAreaList[ipIndex].device
            ) {
              // 心电监护
              if (targetItem.device.type == 1) {
                const deviceParamsList =
                  targetItem?.device?.deviceParamsList || []; // 设备参数列表
                let tempGain =
                  deviceParamsList.filter(
                    (item: any) => item.paramCode === '2',
                  )?.[0]?.paramValue || '1'; // 增益
                let tempaPerSpeed =
                  deviceParamsList.filter(
                    (item: any) => item.paramCode === '1',
                  )?.[0]?.paramValue || '25mm/s'; // 走纸速度
                let canvasInterval = 1;
                switch (tempaPerSpeed) {
                  case '12.5mm/s':
                    canvasInterval = 0.5;
                    break;
                  case '25mm/s':
                    canvasInterval = 1;
                    break;
                  case '50mm/s':
                    canvasInterval = 2;
                    break;
                  default:
                    canvasInterval = 1;
                    break;
                }
                if (
                  data[i].productModel &&
                  data[i].productModel.includes('bxs')
                ) {
                  canvasInterval = Number((canvasInterval / 4).toFixed(2));
                }
                let targetEcgYAxisData = [];
                for (const key in data[i].ecgWaveform) {
                  targetEcgYAxisData.push({
                    minY: -1,
                    maxY: 1,
                    canvasInterval: canvasInterval,
                    color: '#a6f14c',
                    padding: 5,
                    name: key,
                    ecgYAxisData: data[i].ecgWaveform[key],
                    key: data[i].ip + key,
                    id: data[i].ip,
                    leadNumber: key,
                  });
                }
                targetScreenAreaList[ipIndex].device = {
                  ...targetItem.device,
                  ecgYAxisData:
                    systemSettings?.systemPageSize == 9
                      ? targetEcgYAxisData.slice(0, 2)
                      : targetEcgYAxisData.slice(0, 4),
                  respirationWaveform: {
                    //呼吸频率
                    minY:
                      data[i].productModel &&
                      data[i].productModel.includes('bxs')
                        ? -800
                        : -200,
                    maxY:
                      data[i].productModel &&
                      data[i].productModel.includes('bxs')
                        ? 800
                        : 200,
                    color: '#00fffd',
                    canvasInterval: canvasInterval,
                    padding: 5,
                    name: '',
                    ecgYAxisData: data[i].respirationWaveform,
                    key: data[i].ip + 'respirationWaveform',
                    id: data[i].ip + 'respirationWaveform',
                    leadNumber: '',
                    notEcg: true,
                  },
                  spo2Waveform: {
                    minY: -150,
                    maxY: 150,
                    canvasInterval:
                      data[i].productModel &&
                      data[i].productModel.includes('bxs')
                        ? Number((canvasInterval * 2).toFixed(2))
                        : canvasInterval,
                    color: '#31a0ff',
                    padding: 5,
                    name: '',
                    ecgYAxisData: data[i].spo2Waveform,
                    key: data[i].ip + 'spo2Waveform',
                    id: data[i].ip + 'spo2Waveform',
                    leadNumber: '',
                    notEcg: true,
                  },
                };
                targetScreenAreaList[ipIndex] = {
                  ...targetScreenAreaList[ipIndex],
                  ...data[i],
                  gain: tempGain, // 增益
                  ecgFlag: true,
                };
              }
            }
            if (maxAlarmLevelTarget < data[i].maxAlarmLevel) {
              maxAlarmLevelTarget = data[i].maxAlarmLevel;
            }
          }
        }
        setAlarmLevel(String(maxAlarmLevelTarget));
        setScreenAreaList(_.cloneDeep(targetScreenAreaList));
      }
    }, 80);
  };
  const sendWsData = () => {
    if (wsRef?.current) {
      sendWsDataInterval = setInterval(() => {
        if (!wsRef?.current) {
          sendWsDataInterval && window.clearInterval(sendWsDataInterval);
        } else {
          wsRef?.current?.readyState == 1 &&
            wsRef?.current?.send('I am connect');
        }
      }, 3000);
    } else {
      sendWsDataInterval && window.clearInterval(sendWsDataInterval);
    }
  };
  const handleChangeScreen = (num: number) => {
    if (num != pageNum) {
      window.open(`/dashBoard?pageNum=${num}`);
    }
  };
  const handleOption = async (type: string, itemData: any) => {
    setmodItem({
      modKey: type,
      itemData: itemData,
    });
    if (type === 'ScreenAreaPatientMsg') {
      ScreenAreaPatientMsgRef?.current?.handleModalShow(itemData);
    } else if (type === 'PatientLeave') {
      modalConfirmRef?.current?.handleModalShow('该患者确定出院?');
    } else if (type === 'PatientDetail') {
      goPersonalHomePage();
    } else if (type === 'AlarmLimit') {
      if (itemData?.patient?.id) {
        AlarmLimitRef?.current?.handleModalShow(itemData);
      }
    }
  };
  const modalSuccessCallback = async () => {
    if (modItem.modKey === 'PatientLeave') {
      const res = await patientDischarged({
        patientId: modItem?.itemData?.patient?.id,
      });
      if (res?.code === 200) {
        message.success('解绑成功');
        modalConfirmRef?.current?.handleModalShow();
        window.location.reload();
        return true;
      }
    }
  };
  const goPersonalHomePage = () => {
    if (modItem?.itemData?.id) {
      sendWsDataInterval && window.clearInterval(sendWsDataInterval);
      wsRef?.current && wsRef.current.close();
      history.push({
        pathname: '/personalHomePage',
        search: stringify({
          patientId: modItem?.itemData?.patient?.id || '',
          screenAreaId: modItem?.itemData?.id || '',
        }),
      });
    }
  };

  useEffect(() => {
    initData();
    return () => {
      if (timer) {
        window.clearInterval(timer);
      }
      if (setIntervalFun) {
        window.clearInterval(setIntervalFun);
      }
      if (checkWebSocketFun) {
        clearInterval(checkWebSocketFun);
      }
      if (sendWsDataInterval) {
        clearInterval(sendWsDataInterval);
      }
      if (intervalRef) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  useEffect(() => {
    if (screenAreaList.length > 0) {
      CreateMultipleCon();
    }
  }, [screenAreaList]);
  useEffect(() => {
    if (systemSettings?.systemPageSize == 2) {
      const index = screenAreaList.findIndex((its: any) => {
        return its?.alarms?.length > 0;
      });
      if (index > -1) {
        intervalRef.current = setInterval(() => {
          const debouncedAlarmsLength1 = screenAreaList?.[0]?.alarms?.length;
          const debouncedAlarmsLength2 = screenAreaList?.[1]?.alarms?.length;
          const oldCurrentIndex = currentIndex.current;
          currentIndex.current = [
            debouncedAlarmsLength1 > 0
              ? (oldCurrentIndex?.[0] + 1) % debouncedAlarmsLength1
              : 0,
            debouncedAlarmsLength2 > 0
              ? (oldCurrentIndex?.[1] + 1) % debouncedAlarmsLength2
              : 0,
          ];
        }, 1000);
      }
    }
  }, [
    systemSettings,
    screenAreaList?.[0]?.alarms?.length,
    screenAreaList?.[1]?.alarms?.length,
  ]);

  useEffect(() => {
    if (scketSuccessFlag) {
      setTimeout(() => {
        drawIntervalFun();
        sendWsData();
      }, 2000);
    }
  }, [scketSuccessFlag]);

  useEffect(() => {
    // 清除旧定时器
    if (alarmLevel == 3 || alarmLevel == 2) {
      if (playAlarmintervalRef.current) {
        clearInterval(playAlarmintervalRef.current);
        playAlarmintervalRef.current = null;
      }
      playAlarmintervalRef.current = setInterval(() => {
        videoRef?.current && videoRef?.current.play();
      }, 10000);
    }
    return () => {
      if (playAlarmintervalRef.current) {
        clearInterval(playAlarmintervalRef.current);
        playAlarmintervalRef.current = null;
      }
    };
  }, [alarmLevel]);

  return (
    <div className="dashboard-wrapper">
      <div className="header">
        <div className="left">
          <div
            className={pageNum == 1 ? 'active circle-num' : 'circle-num'}
            onClick={() => handleChangeScreen(1)}
          >
            1
          </div>
          <div
            className={pageNum == 2 ? 'active circle-num' : 'circle-num'}
            onClick={() => handleChangeScreen(2)}
          >
            2
          </div>
          <div
            className={pageNum == 3 ? 'active circle-num' : 'circle-num'}
            onClick={() => handleChangeScreen(3)}
          >
            3
          </div>
          <SettingOutlined
            onClick={() => {
              window.open(`/patientMsg`);
            }}
            className="main-system"
          />
        </div>
        <div className="title">中央监护系统</div>
        <div className="right">
          <div className="time">{nowTime}</div>
        </div>
      </div>
      {systemSettings?.systemPageSize == 2 && (
        <div className="double-screen-wrapper">
          {screenAreaList.map((its: any, inx: number) => {
            const patientLimits = its?.patient?.patientLimits || [];
            //心率  heartRate
            const heartRateObj =
              patientLimits.find((its: any) => {
                return its.itemCode === 'heartRate';
              }) || {};
            //温度1  temperature1
            const temperature1Obj =
              patientLimits.find((its: any) => {
                return its.itemCode === 'temperature1';
              }) || {};
            //温度2  temperature2
            const temperature2Obj =
              patientLimits.find((its: any) => {
                return its.itemCode === 'temperature2';
              }) || {};
            //呼吸
            const respirationRateObj =
              patientLimits.find((its: any) => {
                return its.itemCode === 'respirationRate';
              }) || {};
            //血氧
            const spo2ValueObj =
              patientLimits.find((its: any) => {
                return its.itemCode === 'spo2Value';
              }) || {};
            const targetAlarms = its?.alarms?.map((alarmsItems: any) => {
              for (const key in ALARM_THRESHOLD_MAP) {
                if (alarmsItems.msg.includes(key)) {
                  return {
                    level: alarmsItems.level,
                    msg: alarmsItems.msg.replace(
                      key,
                      ALARM_THRESHOLD_MAP[
                        key as keyof typeof ALARM_THRESHOLD_MAP
                      ],
                    ),
                  };
                }
              }
            });
            return (
              <div className="double-screen-item">
                <div className="user-info-wrapper">
                  {/* 操作 */}
                  <div className="option-wrapper">
                    <Dropdown
                      trigger={['click']}
                      menu={{
                        items: [
                          {
                            label: '分区关联',
                            key: 'ScreenAreaPatientMsg',
                            onClick: ({ domEvent }) => {
                              domEvent.stopPropagation();
                              handleOption('ScreenAreaPatientMsg', its);
                            },
                          },
                          {
                            label: '患者离院',
                            key: 'PatientLeave',
                            disabled: !its?.patient?.id,
                            onClick: ({ domEvent }) => {
                              domEvent.stopPropagation();
                              handleOption('PatientLeave', its);
                            },
                          },
                          {
                            label: '详情视图',
                            key: 'PatientDetail',
                            disabled: !its?.patient?.id,
                            onClick: ({ domEvent }) => {
                              domEvent.stopPropagation();
                              handleOption('PatientDetail', its);
                            },
                          },
                        ],
                      }}
                      placement="bottomRight"
                      arrow
                    >
                      <div
                        className="icon2"
                        onClick={(event) => {
                          event.stopPropagation(); // 阻止事件冒泡
                        }}
                      >
                        <img src={partMsg} alt="" />
                      </div>
                    </Dropdown>
                  </div>
                  <div className="patient-info">
                    {/* manPng */}
                    {its?.patient?.sex && (
                      <>
                        {its?.patient?.sex == 1 ? (
                          <img src={manPng} alt="" />
                        ) : (
                          <img src={womanPng} alt="" />
                        )}
                      </>
                    )}
                    {its?.patient?.name || '---'}
                    {its?.patient?.ward?.name && (
                      <> {its?.patient?.ward?.name}</>
                    )}
                    {its?.patient?.ward?.bed?.code && (
                      <> {its?.patient?.ward?.bed?.code}</>
                    )}
                  </div>
                </div>
                <div
                  className="screen-item"
                  onClick={() => handleOption('AlarmLimit', its)}
                >
                  {its?.status === 'offline' ? (
                    <div className="device-offline">设备离线</div>
                  ) : (
                    <>
                      <div className="chart-collection-item ecg-chart">
                        <div className="chart-inner-wrapper">
                          {its?.device?.ecgYAxisData &&
                          its?.device?.ecgYAxisData?.length > 0 ? (
                            <>
                              {its.device.ecgYAxisData?.map((items: any) => {
                                return (
                                  <div
                                    className={`ecg-charts-item  item_${its.device.ecgYAxisData?.length}`}
                                    key={items.key}
                                  >
                                    <EcgCharts
                                      itemData={{
                                        ...items,
                                        gain: its?.gain || 1,
                                        ecgFlag: its?.ecgFlag || false,
                                      }}
                                    />
                                  </div>
                                );
                              })}
                            </>
                          ) : (
                            <div className="no-data">暂无数据</div>
                          )}
                        </div>
                        <div className="ecg-desc-wrapper">
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">ECG</div>
                                <div className="title2">bpm</div>
                              </div>
                              {heartRateObj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>{heartRateObj?.upperLimit || '-'}</div>
                                  <div>{heartRateObj?.lowerLimit || '-'}</div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                heartRateObj.alarmSwitch === '1' &&
                                (its.heartRate > heartRateObj.upperLimit ||
                                  its.heartRate < heartRateObj.lowerLimit)
                                  ? heartRateObj.level == 3
                                    ? 'title3 notice'
                                    : heartRateObj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {its.heartRate}
                            </div>
                          </div>
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">温度1</div>
                                <div className="title2">T</div>
                              </div>
                              {temperature1Obj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>
                                    {temperature1Obj?.upperLimit || '-'}
                                  </div>
                                  <div>
                                    {temperature1Obj?.lowerLimit || '-'}
                                  </div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                temperature1Obj.alarmSwitch === '1' &&
                                (its.temperature1 >
                                  temperature1Obj.upperLimit ||
                                  its.temperature1 < temperature1Obj.lowerLimit)
                                  ? temperature1Obj.level == 3
                                    ? 'title3 notice'
                                    : temperature1Obj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {its.temperature1}
                            </div>
                          </div>
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">温度2</div>
                                <div className="title2">T</div>
                              </div>
                              {temperature2Obj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>
                                    {temperature2Obj?.upperLimit || '-'}
                                  </div>
                                  <div>
                                    {temperature2Obj?.lowerLimit || '-'}
                                  </div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                temperature2Obj.alarmSwitch === '1' &&
                                (its.temperature2 >
                                  temperature2Obj.upperLimit ||
                                  its.temperature2 < temperature2Obj.lowerLimit)
                                  ? temperature2Obj.level == 3
                                    ? 'title3 notice'
                                    : temperature2Obj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {its.temperature2}
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="chart-collection-item">
                        <div className="chart-inner-wrapper">
                          {its?.device?.respirationWaveform ? (
                            <div className="ecg-charts-item">
                              <EcgCharts
                                itemData={its?.device?.respirationWaveform}
                              />
                            </div>
                          ) : (
                            <div className="no-data">暂无数据</div>
                          )}
                        </div>
                        <div className="ecg-desc-wrapper">
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">呼吸</div>
                                <div className="title2">bpm</div>
                              </div>
                              {respirationRateObj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>
                                    {respirationRateObj?.upperLimit || '-'}
                                  </div>
                                  <div>
                                    {temperature1Obj?.lowerLimit || '-'}
                                  </div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                respirationRateObj.alarmSwitch === '1' &&
                                (its.respirationRate >
                                  respirationRateObj.upperLimit ||
                                  its.respirationRate <
                                    respirationRateObj.lowerLimit)
                                  ? respirationRateObj.level == 3
                                    ? 'title3 notice'
                                    : respirationRateObj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {its.respirationRate}
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="chart-collection-item">
                        <div className="chart-inner-wrapper">
                          {its?.device?.spo2Waveform ? (
                            <div
                              className="ecg-charts-item"
                              key={its?.device.spo2Waveform.key}
                            >
                              <EcgCharts itemData={its?.device.spo2Waveform} />
                            </div>
                          ) : (
                            <div className="no-data">暂无数据</div>
                          )}
                        </div>
                        <div className="ecg-desc-wrapper">
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">SpO2</div>
                                <div className="title2">%</div>
                              </div>
                              {spo2ValueObj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>{spo2ValueObj?.upperLimit || '-'}</div>
                                  <div>{spo2ValueObj?.lowerLimit || '-'}</div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                spo2ValueObj.alarmSwitch == 1 &&
                                (its.spo2Value > spo2ValueObj.upperLimit ||
                                  its.spo2Value < spo2ValueObj.lowerLimit)
                                  ? spo2ValueObj.level == 3
                                    ? 'title3 notice'
                                    : spo2ValueObj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {its.spo2Value}
                            </div>
                          </div>
                        </div>
                      </div>
                    </>
                  )}
                </div>
                {/* 报警 */}
                {targetAlarms?.length > 0 && (
                  <Popconfirm
                    title="生理报警"
                    icon={<></>}
                    showCancel={false}
                    okType="default"
                    okText="关闭"
                    onConfirm={() => {}}
                    description={() => {
                      return (
                        <div className="alarm-list-wrapper">
                          {targetAlarms.map((items: any, index: number) => {
                            return (
                              <div
                                className={
                                  targetAlarms[index]?.level == 2
                                    ? 'alarm-item-wrapper medium'
                                    : targetAlarms[index]?.level == 3
                                    ? 'alarm-item-wrapper high'
                                    : 'alarm-item-wrapper'
                                }
                                key={index + '-alarm-item-wrapper'}
                              >
                                <p className="alarm-msg-content">{items.msg}</p>
                              </div>
                            );
                          })}
                        </div>
                      );
                    }}
                  >
                    {targetAlarms[currentIndex?.current?.[inx]] && (
                      <div
                        className={
                          targetAlarms[currentIndex?.current?.[inx]]?.level == 2
                            ? 'alarm-show-wrapper medium'
                            : targetAlarms[currentIndex?.current?.[inx]]
                                ?.level == 3
                            ? 'alarm-show-wrapper high'
                            : 'alarm-show-wrapper'
                        }
                      >
                        <p
                          className="alarm-msg-content"
                          dangerouslySetInnerHTML={{
                            __html:
                              targetAlarms[currentIndex?.current?.[inx]].msg,
                          }}
                        />
                        <EllipsisOutlined className="alarm-msg-icon" />
                      </div>
                    )}
                  </Popconfirm>
                )}
              </div>
            );
          })}
        </div>
      )}
      {systemSettings?.systemPageSize == 9 && (
        <div className="ecg-show-list">
          {screenAreaList.map((its: any, inx: number) => {
            return (
              <div className="ecg-show-item" key={inx + '_screen' + inx}>
                <EcgModule
                  itemData={{ ...its }}
                  key={inx + '_screen' + inx + '_ecgModule'}
                  onCloseWs={() => {
                    sendWsDataInterval &&
                      window.clearInterval(sendWsDataInterval);
                    wsRef?.current && wsRef.current.close();
                  }}
                  refreshList={() => window.location.reload()}
                />
              </div>
            );
          })}
        </div>
      )}
      <video
        ref={videoRef}
        src={alarmLevel == 3 ? highMp3 : alarmLevel == 2 ? middleMp3 : ''}
        width="0"
        height="0"
        playsInline
        preload="metadata"
        autoPlay
        style={{
          display: 'none',
        }}
      />
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
      <ScreenAreaPatientMsg
        ref={ScreenAreaPatientMsgRef}
        refreshList={() => window.location.reload()}
        ecgModuleItem={modItem?.itemData}
      />
      {/* 报警限判断 */}
      <AlarmLimit
        ref={AlarmLimitRef}
        refreshList={() => window.location.reload()}
      />
    </div>
  );
}
